package cn.dyhack.bibiscan.aop;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import cn.dyhack.bibiscan.util.JwtUtils;

/**
 * 
 * 用户切面类
 *
 * @author zhangke
 * @since 1.0.0
 */
@Component
@Aspect
public class UserAspect {

    private static final Logger LOG = LoggerFactory.getLogger(UserAspect.class);

    /**
     * 
     * 定义切点
     *
     * @author zhangke
     * @since 1.0.0
     */
    @Pointcut("@annotation(cn.dyhack.bibiscan.aop.UserTokenValidAnnotation)")
    public void doAspect() {
        System.out.println("");

    }

    @Around("doAspect()")
    public Object doAround(ProceedingJoinPoint joinPoint) {

        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        LOG.debug("进入切面,准备调用权限验证方法");
        LOG.debug("获取目标方法的参数");
        Object[] parameters = signature.getMethod()
                .getParameters();
        Object[] args = joinPoint.getArgs(); 
        for (int i = 0; i < args.length; i++) {
            Object parameter = args[i];
            try {

                if ( parameter instanceof HttpServletRequest) {
                    if (validate(((HttpServletRequest) parameter).getHeader("X-USER-TOKEN"))) {
                        LOG.debug("token校验成功");
                        try {
                            return joinPoint.proceed();
                        } catch (Throwable e) {
                            e.printStackTrace();
                            throw new IllegalArgumentException("认证失败");
                        }
                    } else {
                        LOG.error("token校验失败");
                        throw new IllegalArgumentException("认证失败");
                    }
                }
                else {
                    continue;
                }
            } catch (ClassCastException e) {
                
            }

        }
        return parameters;

    }

    /**
     * 
     * 权限验证函数
     *
     * @return 验证失败返回false,成功返回true
     * @author zhangke
     * @since 1.0.0
     */
    private boolean validate(String token) {

        try {
            JwtUtils.verifyToken(token);
            return true;
        } catch (Exception e) {
            LOG.error("token校验失败");
            e.printStackTrace();
            return false;
        }

    }

}
